package top.pengdong.pictureShare.userAuth.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpResponse;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import top.pengdong.pictureShare.common.model.LoginVal;
import top.pengdong.pictureShare.common.model.PageUtils;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.model.SysConstant;
import top.pengdong.pictureShare.common.pojo.RegisterUser;
import top.pengdong.pictureShare.common.utils.Address;
import top.pengdong.pictureShare.common.utils.IPAddress;
import top.pengdong.pictureShare.common.utils.OauthUtils;
import top.pengdong.pictureShare.userAuth.entity.*;
import top.pengdong.pictureShare.userAuth.feign.tweet.TweetFeignServer;
import top.pengdong.pictureShare.userAuth.service.TRoleService;
import top.pengdong.pictureShare.userAuth.service.TUserRelationService;
import top.pengdong.pictureShare.userAuth.service.TUserRoleService;
import top.pengdong.pictureShare.userAuth.service.TUsersService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;


/**
 * 用户表
 *
 * @author chenshun
 * @email pengshi12138@outlook.com
 * @date 2022-04-18 18:23:15
 */
@Slf4j
@RestController
@RequestMapping("api/user")
public class TUsersController {
    @Autowired
    private TUsersService tUsersService;

    @Autowired
    private TRoleService tRoleService;

    @Autowired
    private TUserRoleService tUserRoleService;

    @Autowired
    private TweetFeignServer tweetFeignServer;

    @Autowired
    private TUserRelationService tUserRelationService;

    private String baseUrl = Address.DOMAIN;


    @RequestMapping("/is_ban")
    public Boolean isBan(@RequestParam Integer userId) {
        return tUsersService.getById(userId).getStatus() == 1 ? false : true;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody TUsersEntity tUsers){
        tUsersService.getBaseMapper().insert(tUsers);
        TUserRoleEntity tUserRoleEntity = new TUserRoleEntity();
        tUserRoleEntity.setUserId(tUsers.getId());
        // TODO 验证部分还要改进
        if (tUsers.getRole() == null) {
            tUserRoleEntity.setRoleId(1L);
        } else {
            TRoleEntity name = tRoleService.getBaseMapper().selectOne(
                    new QueryWrapper<TRoleEntity>().eq("name", tUsers.getRole()));
            if (name == null) tUserRoleEntity.setRoleId(1L);
            else tUserRoleEntity.setRoleId(name.getId());
        }

        tUserRoleService.save(tUserRoleEntity);
        return R.ok();
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tUsersService.queryPage(params);

        return R.ok().put("result", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public TUsersEntity info(@PathVariable("id") Long id){
        TUsersEntity tUsers = tUsersService.getById(id);

        return tUsers;
    }


    @RequestMapping("/adminUpdate")
    public R admin_update(@RequestBody TUsersEntity tUsers){
        tUsersService.updateById(tUsers);

        return R.ok();
    }

    @RequestMapping("/adminDelete")
    public R admin_update(@RequestBody Long[] ids){
        tUsersService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 以上是后台管理接口
     */

    /**
     * 返回用户新
     */
    @RequestMapping("/user_info/{userId}")
    public R info(@PathVariable("userId") String userId){
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) {
            TUsersEntity byId = tUsersService.getById(userId);
            if (byId != null) {
                return R.ok().put("result", byId);
            }
            return R.ok("参数错误");
        } else {
            TUsersEntity byId = tUsersService.getById(loginVal.getUserId());
            return R.ok().put("result", byId);
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody TUsersEntity tUsers){
        LoginVal loginVal = OauthUtils.getCurrentUser();
        tUsers.setId(Long.parseLong(loginVal.getUserId()));
		tUsersService.updateByIdWithPassword(tUsers);

        return R.ok("更新成功");
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(){
        LoginVal loginVal = OauthUtils.getCurrentUser();
        TUsersEntity byId = tUsersService.getById(loginVal.getUserId());
        byId.setStatus(0);

        tUsersService.updateById(byId);
        return R.ok("删除成功");
    }

    /**
     * 创建用户
     * @param registerUser
     * @return
     */
    @PostMapping("/create")
    public R createAccount(@RequestBody @Valid RegisterUser registerUser, BindingResult bindingResult, HttpServletRequest httpServletRequest) {

        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors =
                    bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String message = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                //这样就可以罗列出有问题的字段和错误提示信息
                return R.error(400, field + " " + message);
            }

        }
        if (!registerUser.getPassword().equals(registerUser.getPassword2())) {
            return R.error(400, "确认密码和密码不一致");
        }
        // 进行ip限制访问操作
        String ip = IPAddress.getIpAddr(httpServletRequest);
        log.info("ip 进行用户注册操作:{}" + ip);
        return tUsersService.createAccount(registerUser, ip);
    }


    /**
     * 激活操作 然后跳转页面
     * @param confirmCode
     * @return
     */
    @GetMapping("/activation")
    public void activationAccount(@RequestParam("confirmCode") String confirmCode,
                                  @RequestParam("mail") String mail,
                                  HttpServletResponse response) {
        // TODO 注册问题
        try {
            log.info("用户注册操作:{}" + mail);
            response.sendRedirect(baseUrl + "/#/?code=" + JSON.toJSONString(tUsersService.activationAccount(confirmCode, mail)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 用户点赞列表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/like")
    public R userLike(@RequestParam Integer page, @RequestParam Integer limit) {
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) return R.error(401, "请登录");
        return R.ok("用户点赞列表").put("result",
                tweetFeignServer.getUserInfoTweets(Long.valueOf(loginVal.getUserId()), 0, page, limit));
    }

    /**
     * 用户分享表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/share")
    public R userShare(@RequestParam Integer page, @RequestParam Integer limit) {
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) return R.error(401, "请登录");
        return R.ok("用户点赞列表").put("result",
                tweetFeignServer.getUserInfoTweets(Long.valueOf(loginVal.getUserId()), 1, page, limit));
    }

    /**
     * 用户收藏列表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/collection")
    public R userCollection(@RequestParam Integer page, @RequestParam Integer limit) {
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) return R.error(401, "请登录");
        return R.ok("用户点赞列表").put("result",
                tweetFeignServer.getUserInfoTweets(Long.valueOf(loginVal.getUserId()), 2, page, limit));
    }


    @GetMapping("/tweet")
    public R getUserTweet(@RequestParam Integer page, @RequestParam Integer limit) {
        LoginVal loginVal = OauthUtils.getCurrentUser();
        return R.ok("用户自身文章").put("result",
                tweetFeignServer.getUserTweets(Long.valueOf(loginVal.getUserId()), page, limit));
    }

    /**
     * 用户关系操作
     */


    /**
     * 用户关注操作
     */
    @GetMapping("/relation")
    public R userRelation(@RequestParam("action") String action,
                          @RequestParam(value = "toUserId", required = false) Long toUserId,
                          @RequestParam(value = "page", required = false) Integer page,
                          @RequestParam(value = "limit", required = false) Integer limit,
                          @RequestParam(value = "type", required = false) String type) {

        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) {
            return R.error(401, "用户未登录");
        }
        // 添加操作
        if ("add".equals(action)) {
            // 查看被关注的userId存在
            TUsersEntity tUsers = tUsersService.getById(toUserId);
            if (tUsers == null) return R.error(400, "参数错误");
            // 判断关系是不是重复了
            if (tUserRelationService.count(new QueryWrapper<TUserRelationEntity>()
                    .eq("user_id", Long.valueOf(loginVal.getUserId()))
                    .eq("follow_id", toUserId)) > 0
            ) {
                return R.error(500, "存在关系");
            }
            TUserRelationEntity tUserRelation = new TUserRelationEntity();
            tUserRelation.setUserId(Long.valueOf(loginVal.getUserId()));
            tUserRelation.setFollowId(tUsers.getId());
            tUserRelation.setVisitCount(0);
            tUserRelation.setStatus(1);
            tUserRelationService.save(tUserRelation);
            return R.ok("添加关系成功");
        } else if ("delete".equals(action)) {
            // 查看被关注的userId存在
            TUsersEntity tUsers = tUsersService.getById(toUserId);
            if (tUsers == null) return R.error(400, "参数错误");
            tUserRelationService.remove(new QueryWrapper<TUserRelationEntity>()
                    .eq("user_id", Long.valueOf(loginVal.getUserId()))
                    .eq("follow_id", toUserId));
            return R.ok("移除关系成功");
        } else if ("info".equals(action)) {
            if (page == null) page = 1;
            if (limit == null) limit = 10;
            return tUserRelationService.getUserRelationInfo(
                    Long.valueOf(loginVal.getUserId()),
                    page,
                    limit,
                    "user_id");
        } else if ("fans".equals(action)) {
            if (page == null) page = 1;
            if (limit == null) limit = 10;
            return tUserRelationService.getUserRelationInfo(
                    Long.valueOf(loginVal.getUserId()),
                    page,
                    limit,
                    "follow_id");
        }
        return R.error(400, "参数错误");
    }

}
